package com.rz.htk.print.util;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.rz.htk.order.entity.Order;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class PrintPdfUtil {

    @Value("${printTempPath}")
    private String printTempPath;
    @Value("${newPrintTempPath}")
    private String newPrintTempPath;
    @Value("${newZiPaiTempPath}")
    private String newZiPaiTempPath;
    @Value("${ziPaiprintTempPath}")
    private String ziPaiprintTempPath;
    @Value("${newUsZiPaiTempPath}")
    private String newUsZiPaiTempPath;

    public void createPdf(List<Order> orders, OutputStream output) {
        List<PdfReader> pdfReaderList = new ArrayList<>();
        try {

            BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            for (int i = 0; i < orders.size(); i++) {
                Order order = orders.get(i);
                if (order.getPrdCode().equals("HTK_P0010")) {

                    PdfReader reader = new PdfReader(newPrintTempPath);
                    ByteArrayOutputStream ba = new ByteArrayOutputStream();
                    PdfReader pdfReader;
                    PdfStamper ps = new PdfStamper(reader, ba);
                    AcroFields form = ps.getAcroFields();
                    form.addSubstitutionFont(bf);
                    form.setFieldProperty("reciveName", "textfont", bf, null);
                    form.setField("reciveName", order.getRecipientsName());
                    form.setFieldProperty("phone", "textfont", bf, null);
                    form.setField("phone", order.getRecipientsPhone());
                    form.setFieldProperty("address", "textfont", bf, null);
                    form.setField("address", order.getRecipientsAddress());
                    form.setFieldProperty("price", "textfont", bf, null);
                    form.setField("price", String.valueOf(order.getDsk()));
                    form.setFieldProperty("goods", "textfont", bf, null);
                    form.setField("goods", order.getCommodityName());
                    form.setFieldProperty("sendTime", "textfont", bf, null);
                    form.setField("sendTime", "日期：" + order.getShipDate() + "      序号：1");
                    form.setFieldProperty("dzCode", "textfont", bf, null);
                    form.setField("dzCode", order.getEsid());
                    form.setFieldProperty("fzCode", "textfont", bf, null);
                    form.setField("fzCode", order.getSsid() + "-" + order.getAfterCode().substring(order.getAfterCode().length() - 4));
                    form.setFieldProperty("fzRmk", "textfont", bf, null);
                    form.setField("fzRmk", "八里 > " + order.getEsna());
                    form.setFieldProperty("orderNum", "textfont", bf, null);
                    form.setField("orderNum", "出货单号：" + order.getAfterCode());
                    form.setFieldProperty("tempBasic", "textfont", bf, null);
                    form.setField("tempBasic", "共1件之1");
                    form.setFieldProperty("msg", "textfont", bf, null);
                    form.setField("msg", order.getCommodityDesc());

                    form.setFieldProperty("tm1No", "textfont", bf, null);
                    form.setField("tm1No", order.getAfterCode());
                    form.setFieldProperty("tm3No", "textfont", bf, null);
                    form.setField("tm3No", order.getAfterCode());

                    Barcode128 barcode128 = new Barcode128();
                    barcode128.setSize(10);
                    barcode128.setBarHeight(35);
                    barcode128.setBaseline(10);
                    barcode128.setX(1.3f);
                    barcode128.setCode(order.getAfterCode());
                    barcode128.setStartStopText(false);
                    barcode128.setExtended(true);

                    AcroFields.FieldPosition fieldPosition = form.getFieldPositions("tm1").get(0);
                    PdfContentByte cb = ps.getOverContent(1);
                    Image image128 = barcode128.createImageWithBarcode(cb, BaseColor.BLACK, BaseColor.WHITE);
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + 8, fieldPosition.position.getBottom() - 8);
                    cb.addImage(image128);

                    barcode128.setX(1.3f);
                    AcroFields.FieldPosition fieldPositionTm2 = form.getFieldPositions("tm2").get(0);
                    PdfContentByte cbTm2 = ps.getOverContent(1);
                    Image image128Tm2 = barcode128.createImageWithBarcode(cbTm2, BaseColor.BLACK, BaseColor.WHITE);
                    image128Tm2.setAbsolutePosition(fieldPositionTm2.position.getLeft() + 5, fieldPositionTm2.position.getBottom() - 8);
                    cbTm2.addImage(image128Tm2);

                    barcode128.setBarHeight(30);
                    barcode128.setX(1.3f);
                    AcroFields.FieldPosition fieldPositionTm3 = form.getFieldPositions("tm3").get(0);
                    PdfContentByte cbTm3 = ps.getOverContent(1);
                    Image image128Tm3 = barcode128.createImageWithBarcode(cbTm3, BaseColor.BLACK, BaseColor.WHITE);
                    image128Tm3.setAbsolutePosition(fieldPositionTm3.position.getLeft(), fieldPositionTm3.position.getBottom() - 10);
                    cbTm3.addImage(image128Tm3);

//                    Barcode128 barcode128 = new Barcode128();
//                    //字号                   
//                    barcode128.setSize(10);
//                    //条码高度                   
//                    barcode128.setBarHeight(35);
//                    //条码与数字间距
//                    barcode128.setBaseline(10);
//                    barcode128.setX(1.5f);
//                    //条码值
//                    barcode128.setCode(order.getAfterCode());
//                    barcode128.setStartStopText(false);
//                    barcode128.setExtended(true);
//                    barcode128.setFont(null);
//
//                    AcroFields.FieldPosition fieldPosition = form.getFieldPositions("tm1").get(0);
//                    PdfContentByte cb = ps.getOverContent(1);
//                    Image image128 = barcode128.createImageWithBarcode(cb, BaseColor.BLACK,BaseColor.WHITE);
////                float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
//                    image128.setAbsolutePosition(fieldPosition.position.getLeft()+5, fieldPosition.position.getBottom());
//                    cb.addImage(image128);
//
//                    barcode128.setX(1f);
//                    AcroFields.FieldPosition fieldPositionTm2 = form.getFieldPositions("tm2").get(0);
//                    PdfContentByte cbTm2 = ps.getOverContent(1);
//                    Image image128Tm2 = barcode128.createImageWithBarcode(cbTm2, BaseColor.BLACK, BaseColor.WHITE);
//                    image128Tm2.setAbsolutePosition(fieldPositionTm2.position.getLeft()+5, fieldPositionTm2.position.getBottom());
//                    cbTm2.addImage(image128Tm2);
                    ps.setFormFlattening(true);
                    ps.close();
                    pdfReader = new PdfReader(ba.toByteArray());
                    pdfReaderList.add(pdfReader);
                } else if (order.getPrdCode().equals("HTK_P0017")) {
                    PdfReader reader = new PdfReader(newZiPaiTempPath);
                    ByteArrayOutputStream ba = new ByteArrayOutputStream();
                    PdfReader pdfReader;
                    PdfStamper ps = new PdfStamper(reader, ba);
                    AcroFields form = ps.getAcroFields();
                    form.addSubstitutionFont(bf);
                    form.setFieldProperty("reciveName", "textfont", bf, null);
                    form.setField("reciveName", order.getRecipientsName());
                    form.setFieldProperty("phone", "textfont", bf, null);
                    form.setField("phone", order.getRecipientsPhone());
                    form.setFieldProperty("address", "textfont", bf, null);
                    form.setField("address", order.getRecipientsAddress());
                    form.setFieldProperty("price", "textfont", bf, null);
                    form.setField("price", String.valueOf(order.getDsk()));
                    form.setFieldProperty("goods", "textfont", bf, null);
                    form.setField("goods", order.getCommodityName());
                    form.setFieldProperty("sendTime", "textfont", bf, null);
                    form.setField("sendTime", "日期：" + order.getShipDate() + "      序号：1");
                    form.setFieldProperty("dzCode", "textfont", bf, null);
                    form.setField("dzCode", order.getEsid());
                    form.setFieldProperty("fzCode", "textfont", bf, null);
                    form.setField("fzCode", order.getSsid() + "-" + order.getAfterCode().substring(order.getAfterCode().length() - 4));
                    form.setFieldProperty("fzRmk", "textfont", bf, null);
                    form.setField("fzRmk", "八里 > " + order.getEsna());
                    form.setFieldProperty("orderNum", "textfont", bf, null);
                    form.setField("orderNum", "出货单号：" + order.getAfterCode());
                    form.setFieldProperty("tempBasic", "textfont", bf, null);
                    form.setField("tempBasic", "共1件之1");
                    form.setFieldProperty("msg", "textfont", bf, null);
                    form.setField("msg", order.getCommodityDesc());

                    form.setFieldProperty("tm1No", "textfont", bf, null);
                    form.setField("tm1No", order.getAfterCode());
                    form.setFieldProperty("tm3No", "textfont", bf, null);
                    form.setField("tm3No", order.getAfterCode());

                    Barcode128 barcode128 = new Barcode128();
                    barcode128.setSize(10);
                    barcode128.setBarHeight(35);
                    barcode128.setBaseline(10);
                    barcode128.setX(1f);
                    barcode128.setCode(order.getAfterCode());
                    barcode128.setStartStopText(true);
                    barcode128.setExtended(true);

                    AcroFields.FieldPosition fieldPosition = form.getFieldPositions("tm1").get(0);
                    PdfContentByte cb = ps.getOverContent(1);
                    Image image128 = barcode128.createImageWithBarcode(cb, BaseColor.BLACK, BaseColor.WHITE);
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + 8, fieldPosition.position.getBottom() - 8);
                    cb.addImage(image128);

                    barcode128.setX(1f);
                    AcroFields.FieldPosition fieldPositionTm2 = form.getFieldPositions("tm2").get(0);
                    PdfContentByte cbTm2 = ps.getOverContent(1);
                    Image image128Tm2 = barcode128.createImageWithBarcode(cbTm2, BaseColor.BLACK, BaseColor.WHITE);
                    image128Tm2.setAbsolutePosition(fieldPositionTm2.position.getLeft() + 5, fieldPositionTm2.position.getBottom() - 8);
                    cbTm2.addImage(image128Tm2);

                    barcode128.setBarHeight(30);
                    barcode128.setX(1f);
                    AcroFields.FieldPosition fieldPositionTm3 = form.getFieldPositions("tm3").get(0);
                    PdfContentByte cbTm3 = ps.getOverContent(1);
                    Image image128Tm3 = barcode128.createImageWithBarcode(cbTm3, BaseColor.BLACK, BaseColor.WHITE);
                    image128Tm3.setAbsolutePosition(fieldPositionTm3.position.getLeft(), fieldPositionTm3.position.getBottom() - 10);
                    cbTm3.addImage(image128Tm3);

                    ps.setFormFlattening(true);
                    ps.close();
                    pdfReader = new PdfReader(ba.toByteArray());
                    pdfReaderList.add(pdfReader);
                }else if(order.getPrdCode().equals("HTK_P0022") || order.getPrdCode().equals("HTK_P0023")){
                    PdfReader reader = new PdfReader(newUsZiPaiTempPath);
                    ByteArrayOutputStream ba = new ByteArrayOutputStream();
                    PdfReader pdfReader;
                    PdfStamper ps = new PdfStamper(reader, ba);
                    AcroFields form = ps.getAcroFields();
                    form.addSubstitutionFont(bf);
                    form.setFieldProperty("name", "textfont", bf, null);
                    form.setField("name", order.getRecipientsName());
                    form.setFieldProperty("tel", "textfont", bf, null);
                    form.setField("tel", order.getRecipientsPhone());
                    form.setFieldProperty("address", "textfont", bf, null);
                    form.setField("address", order.getRecipientsAddress());
                    form.setFieldProperty("postalcode", "textfont", bf, null);
                    form.setField("postalcode", order.getRecipientsPostcode());
                    form.setFieldProperty("content1", "textfont", bf, null);
                    form.setField("content1", order.getCommodityName());
                    form.setFieldProperty("weight1", "textfont", bf, null);
                    form.setField("weight1", order.getWeight().toString());
                    form.setFieldProperty("value1", "textfont", bf, null);
                    form.setField("value1",order.getPrice() == null ? "" : order.getPrice().toString());

                    form.setFieldProperty("content2", "textfont", bf, null);
                    form.setField("content2", order.getCommodityDesc());
                    form.setFieldProperty("weight2", "textfont", bf, null);
                    form.setField("weight2", order.getWeight().toString());
                    form.setFieldProperty("value2", "textfont", bf, null);
                    form.setField("value2", order.getPrice() == null ? "" : order.getPrice().toString());

                    form.setFieldProperty("tm1No", "textfont", bf, null);
                    form.setField("tm1No", order.getAfterCode());
                    form.setFieldProperty("tm2No", "textfont", bf, null);
                    form.setField("tm2No", order.getAfterCode());

                    Barcode128 barcode128 = new Barcode128();
                    barcode128.setSize(10);
                    barcode128.setBarHeight(25);
                    barcode128.setBaseline(10);
                    barcode128.setX(1.0f);
                    barcode128.setCode(order.getAfterCode());
                    barcode128.setStartStopText(true);
                    barcode128.setExtended(true);

                    AcroFields.FieldPosition fieldPosition = form.getFieldPositions("tm1").get(0);
                    PdfContentByte cb = ps.getOverContent(1);
                    Image image128 = barcode128.createImageWithBarcode(cb, BaseColor.BLACK, BaseColor.WHITE);
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + 8, fieldPosition.position.getBottom() - 15);
                    cb.addImage(image128);

                    barcode128.setX(1.2f);
                    AcroFields.FieldPosition fieldPositionTm2 = form.getFieldPositions("tm2").get(0);
                    PdfContentByte cbTm2 = ps.getOverContent(1);
                    Image image128Tm2 = barcode128.createImageWithBarcode(cbTm2, BaseColor.BLACK, BaseColor.WHITE);
                    image128Tm2.setAbsolutePosition(fieldPositionTm2.position.getLeft() + 10, fieldPositionTm2.position.getBottom() - 15);
                    cbTm2.addImage(image128Tm2);

                    ps.setFormFlattening(true);
                    ps.close();
                    pdfReader = new PdfReader(ba.toByteArray());
                    pdfReaderList.add(pdfReader);
                }
            }
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, output);
            document.open();
            for (int k = 0; k < pdfReaderList.size(); k++) {
                PdfReader pdfReader = pdfReaderList.get(k);
                document.newPage();
                copy.addDocument(pdfReader);
            }
            copy.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Description: 将pdf文件转换为Base64编码
     *
     * @param fin PDF文件流
     * @Author fuyuwei
     * Create Date: 2015年8月3日 下午9:52:30
     */
    public static String PDFToBase64(ByteArrayInputStream fin) {
        BASE64Encoder encoder = new BASE64Encoder();
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        try {
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = fin.read(buffer);
            while (len != -1) {
                bout.write(buffer, 0, len);
                len = fin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
                fin.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Description: 将base64编码内容转换为Pdf
     *
     * @param base64Content，文件的存储路径（含文件名）
     * @Author fuyuwei
     * Create Date: 2015年7月30日 上午9:40:23
     */
    public static void base64StringToPdf(String base64Content, String filePath) {
        BASE64Decoder decoder = new BASE64Decoder();
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            byte[] bytes = decoder.decodeBuffer(base64Content);//base64编码内容转换为字节数组
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File("c://temp//123.pdf");
            File path = file.getParentFile();
            if (!path.exists()) {
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1) {
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //closeStream(bis, fos, bos);
        }
    }

    // outputStream转inputStream
    public ByteArrayInputStream parse(final OutputStream out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) out;
        final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File("C:\\temp\\1db20269-a4f7-45a9-a854-b6b9c5af8d39.pdf"));
            byte[] buffer = new byte[1024000];
            fileInputStream.read(buffer);
            String filecontext = PrintPdfUtil.PDFToBase64(new ByteArrayInputStream(buffer));
            FileWriter writer = new FileWriter(new File("c:\\temp\\pdf.txt"));
            writer.write(filecontext);
            writer.flush();
            writer.close();
            fileInputStream.close();

//            BufferedReader reader = new BufferedReader(new FileReader("c://temp//pdf.txt"));
//            StringBuilder sb = new StringBuilder();
//            String content = "";
//            while (content != null) {
//                content = reader.readLine();
//                if (content == null) {
//                    break;
//                }
//                sb.append(content.trim());
//            }
//            base64StringToPdf(sb.toString(), "");
        } catch (Exception e) {
        }
    }
}
